package com.hrms.hrms_security.utils;

import com.hrms.hrms_security.exception.BusinessException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

public class SecurityUtils {
    /**
     * 获取系统用户名称
     *
     * @return 系统用户名称
     */
    public static String getCurrentUsername() throws BusinessException {
        final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            throw new BusinessException( "当前登录状态过期");
        }
//        Method[] m = authentication.getPrincipal().getClass().getDeclaredMethods();
//        for (int i = 0; i < m.length; i++) {
//            System.out.println(m[i].getName());
//        }
        if (authentication.getPrincipal() instanceof UserDetails) {
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            System.out.println("登陸報錯的系統用戶名"+userDetails);
            return userDetails.getUsername();
        }
        throw new BusinessException("找不到当前登录的信息");
    }

}
